import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_train.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';

import '../common/common_dialog.dart';
import 'controller/eacher_work_train_details_controller.dart';
import 'model/train_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/14.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class TrainTeacherCourseItemWidget3 extends StatefulWidget {
  final CourseAndTeacherBean cubean;
  final int index;

  final isScaffold;

  const TrainTeacherCourseItemWidget3(
      {Key key, this.cubean, this.index, this.isScaffold = true})
      : super(key: key);

  @override
  _TrainTeacherCourseItemWidget3State createState() =>
      _TrainTeacherCourseItemWidget3State();
}

class _TrainTeacherCourseItemWidget3State
    extends State<TrainTeacherCourseItemWidget3>
    with SingleTickerProviderStateMixin, TrainModel {
  @override
  void initState() {
    super.initState();
  }

  List<CourseBean> _list = [];

  @override
  Widget build(BuildContext context) {
    String userName = "无教师";
    if (widget.cubean.userEntity != null) {
      userName = widget.cubean.userEntity.reamName;
    }
    //课程状态  0 未上课  1 正在上课中  2上课完成
    int courseStatues = widget.cubean.courseStatues;

    Color textColor = Color(0xff555555);
    if (courseStatues == 1) {
      textColor = Colors.green;
    } else if (courseStatues == 2) {
      textColor = Colors.blue;
    }

    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(top: 12, right: 12, bottom: 20),
      margin: EdgeInsets.only(top: 6),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(right: 6, left: 6),
            margin: EdgeInsets.only(top: 3),
            child: Text("${widget.cubean.index}"),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Expanded(
                        child: Text(
                      "教师 $userName",
                      style: TextStyle(
                          fontWeight: FontWeight.bold, color: textColor),
                    )),
                    Text(
                      "${widget.cubean.courseStatuesStr}",
                      style: TextStyle(color: textColor),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Text(
                      "${widget.cubean.teacherPeriod}课时",
                      style: TextStyle(color: textColor),
                    ),
                  ],
                ),
                Container(
                  color: Colors.grey[200],
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 4),
                  padding: EdgeInsets.all(4),
                  child: Wrap(
                    crossAxisAlignment: WrapCrossAlignment.start,
                    children: [
                      Text(
                        "培训内容:",
                      ),
                      SizedBox(
                        width: 12,
                      ),
                      Text(
                        widget.cubean.teacherContent,
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff666666),
                        ),
                      ),
                    ],
                  ),
                ),
                buildStartTimeWidget(),
                buildTeacherSginWidget(),
                buildSignFocesWidget(),
                buildSignEndWidget(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  buildSignFocesWidget() {
    return Container(
      color: Colors.grey[200],
      padding: EdgeInsets.all(8),
      margin: EdgeInsets.only(top: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  "开始上课要求:",
                ),
              ),
              buildTeacherStartButton(),
            ],
          ),
          buildTeacherStartButtonTips(),
          Row(
            children: [
              Expanded(
                child: Text(
                  "${widget.cubean.isForceLocation ? "要求使用位置验证 签到位置距离不得超出 ${widget.cubean.forceLocation}m ,开始上课时，学员签到时会根据教师的上课位置来计算签到距离" : "无要求"}  ",
                  style: TextStyle(fontSize: 14, color: Color(0xff666666)),
                ),
              ),
            ],
          ),
          buildCourseCodeWidget(),
        ],
      ),
    );
  }

  buildSignEndWidget() {
    return Container(
      color: Colors.grey[200],
      padding: EdgeInsets.all(8),
      margin: EdgeInsets.only(top: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  "结束上课要求:",
                ),
              ),
              buildTeacherEndButton(),
            ],
          ),
          buildTeacherEndButtonTips(),
        ],
      ),
    );
  }

  buildCourseCodeWidget() {
    String courseCode = widget.cubean.courseCode;
    if (courseCode == null || courseCode.isEmpty) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 10),
      child: Row(
        children: [
          Expanded(
            child: Text(
              "部分用户无法使用位置签到时可以使用随机签到码签到或者签退,可以点击随机码刷新，当点击结束上课时，随机码会刷新，学员可以开始签退",
            ),
          ),
          SizedBox(
            width: 12,
          ),
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              GetBuilder(
                id: widget.cubean.id.toString(),
                tag: widget.cubean.trainId.toString(),
                builder: (TeacherTrainDetailsController controller) {
                  bool isUpdateLoading = controller.getIsUpdateLoading();
                  if (isUpdateLoading) {
                    return LoadingWidget();
                  }
                  CourseAndTeacherBean bean = controller.getUpdateDetails();
                  if (bean != null) {
                    courseCode = bean.courseCode;
                  }
                  return GestureDetector(
                    onTap: () {
                      controller.updateCourseCodeRequest(
                          id: widget.cubean.id,
                          teacherSignRecoderId:
                              widget.cubean.teacherSignRecoderId);
                    },
                    child: Text(
                      courseCode,
                      style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          color: Colors.blue),
                    ),
                  );
                },
              ),
            ],
          )
        ],
      ),
    );
  }

  buildStartTimeWidget() {
    if (widget.cubean.teacherContent == null) {
      return SizedBox();
    }
    return Container(
      color: Colors.grey[200],
      padding: EdgeInsets.all(8),
      margin: EdgeInsets.only(top: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            "培训时间:",
          ),
          Row(
            children: [
              Text(
                "${widget.cubean.beginTime} ~ ",
                style: TextStyle(fontSize: 14, color: Color(0xff666666)),
              ),
              Text(
                "${widget.cubean.endTime} ",
                style: TextStyle(fontSize: 14, color: Color(0xff666666)),
              ),
            ],
          ),
        ],
      ),
    );
  }

  buildTeacherSginUpTimeWidget() {
    if (!widget.cubean.showTeacherTime ||
        widget.cubean.teacherSignEndTime == null) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 4),
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            "结束上课时间： ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          Text(
            "${widget.cubean.teacherSignEndTime} ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
        ],
      ),
    );
  }

  buildTeacherSginWidget() {
    if (!widget.cubean.showTeacherTime ||
        widget.cubean.teacherSignStartTime == null) {
      return SizedBox();
    }
    return Container(
      margin: EdgeInsets.only(top: 10),
      color: Colors.grey[200],
      padding: EdgeInsets.all(3),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            children: [
              Text("教师上课签到信息"),
            ],
          ),
          buildTeacherSginToTimeWidget(),
          buildTeacherSginUpTimeWidget(),
        ],
      ),
    );
  }

  buildTeacherSginToTimeWidget() {
    return Container(
      child: Wrap(
        crossAxisAlignment: WrapCrossAlignment.center,
        children: [
          Text(
            "开始上课时间： ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
          Text(
            "${widget.cubean.teacherSignStartTime} ",
            style: TextStyle(fontSize: 14, color: Color(0xff666666)),
          ),
        ],
      ),
    );
  }

  buildTeacherStartButton() {
    bool showTeacherStartSign = widget.cubean.showTeacherStartSign;
    if (showTeacherStartSign) {
      return ElevatedButton(
          onPressed: () {
            showStartCourseTips();
          },
          child: _signLoading ? LoadingWidget() : Text("开始上课"));
    }
    return SizedBox();
  }

  buildTeacherEndButton() {
    bool showTeacherEndSign = widget.cubean.showTeacherEndSign;
    if (showTeacherEndSign) {
      return ElevatedButton(
          onPressed: () {
            showEndCourseTips();
          },
          child: _signLoading ? LoadingWidget() : Text("结束上课"));
    }
    return SizedBox();
  }

  buildTeacherStartButtonTips() {
    bool showTeacherStartTips = widget.cubean.showTeacherStartTips;
    if (!showTeacherStartTips) {
      return SizedBox();
    }
    String showTeacherStartTips1 = widget.cubean.showTeacherStartTips1;
    if (showTeacherStartTips1.isEmpty) {
      return SizedBox();
    }
    return Text(
      showTeacherStartTips1,
      style: TextStyle(color: Colors.red),
    );
  }

  buildTeacherEndButtonTips() {
    bool showTeacherEndTips = widget.cubean.showTeacherEndTips;
    if (!showTeacherEndTips) {
      return SizedBox();
    }
    String showTeacherEndTips1 = widget.cubean.showTeacherEndTips1;
    if (showTeacherEndTips1.isEmpty) {
      return SizedBox();
    }
    return Text(
      showTeacherEndTips1,
      style: TextStyle(color: Colors.red),
    );
  }

  bool _signLoading = false;
  bool _signUpLoading = false;

  ///-----------------------教师 start -----------------------------------------------------------------------
  ///开始上课
  showStartCourseTips() async {
    bool isForceLocation = widget.cubean.isForceLocation;
    num forceLocation = widget.cubean.forceLocation;
    String userAddress = UserHelper.getInstance.userAddress;
    if ((userAddress == null || userAddress.isEmpty) && isForceLocation) {
      dynamic result = await Get.defaultDialog(
          radius: 4,
          title: "温馨提示",
          content: Container(
            constraints: BoxConstraints(maxHeight: 600),
            child: Text("获取位置信息失败暂时无法开始上课"),
          ),
          confirm: Container(
            alignment: Alignment.center,
            child: TextButton(
              onPressed: () {
                Get.back(result: true);
              },
              child: Text(
                "确认",
                style: TextStyle(color: Colors.blue),
              ),
            ),
            width: 100,
          ),
          cancel: Container(
            alignment: Alignment.center,
            child: TextButton(
              onPressed: () {
                Get.back(result: true);
              },
              child: Text(
                "取消",
                style: TextStyle(color: Colors.blue),
              ),
            ),
            width: 100,
          ));
      return;
    }
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        selectText: "确定",
        contentMessag: "确定开始上课吗??",
        selectCallBack: () {
          teacherSignRequest();
        });
  }

  void teacherSignRequest() async {
    setState(() {
      _signLoading = true;
    });
    TrainCourseSignBean trainCourseSignBean =
        await trainTeacherCourseSign(widget.cubean);
    if (trainCourseSignBean != null) {
      ToastUtils.showToast("操作成功");
      widget.cubean.teacherSignStartTime = trainCourseSignBean.signToTime;
      widget.cubean.teacherSignRecoderId = trainCourseSignBean.id;
      widget.cubean.courseCode = trainCourseSignBean.courseCode;
      widget.cubean.showTeacherStartSign = false;
      widget.cubean.showTeacherEndSign = true;
      widget.cubean.courseStatues = 1;
      widget.cubean.courseStatuesStr = "正在上课中";
      if (Get.isRegistered<TeacherTrainDetailsController>(
          tag: widget.cubean.trainId.toString())) {
        Get.find<TeacherTrainDetailsController>(
                tag: widget.cubean.trainId.toString())
            .update(["root"]);
      }
    }
    setState(() {
      _signLoading = false;
    });
  }

  showEndCourseTips() {
    showCommonAlertDialog(
        context: context,
        cancleText: "取消",
        selectText: "确定",
        contentMessag: "确定结束上课吗??",
        selectCallBack: () {
          teacherSignUpRequest();
        });
  }

  void teacherSignUpRequest() async {
    setState(() {
      _signLoading = true;
    });
    TrainCourseSignBean trainCourseSignBean =
        await trainTeacherCourseSignUp(widget.cubean);
    if (trainCourseSignBean != null) {
      ToastUtils.showToast("操作成功");
      widget.cubean.teacherSignEndTime = trainCourseSignBean.signUpTime;
      widget.cubean.showTeacherStartSign = false;
      widget.cubean.showTeacherEndSign = false;
      widget.cubean.courseStatues = 2;
      widget.cubean.courseStatuesStr = "已上课";

      if (Get.isRegistered<TeacherTrainDetailsController>(
          tag: widget.cubean.trainId.toString())) {
        Get.find<TeacherTrainDetailsController>(
                tag: widget.cubean.trainId.toString())
            .update(["root"]);
        Get.find<TeacherTrainDetailsController>(
                tag: widget.cubean.trainId.toString())
            .updateCourseCodeRequest(
                click: true,
                id: widget.cubean.id,
                teacherSignRecoderId: widget.cubean.teacherSignRecoderId);
      }
    }
    setState(() {
      _signLoading = false;
    });
  }
}
